<template>
  <el-dialog title="人员列表" append-to-body width="80%" custom-class="scrollable-dialog" :visible.sync="visible">
    <el-tabs v-model="activeName" type="card" @tab-click="tabChange">
      <el-tab-pane label="供应商" name="2"></el-tab-pane>
      <el-tab-pane label="内部用户" name="1"></el-tab-pane>
    </el-tabs>

    <template v-if="activeName == '2'">
      <div class="pass-box">
        <div class="pass-tree">
          <div class="line-ber">
            <label class="line-label">入库类别</label>
          </div>
          <div class="tree-prop">
            <el-input
              v-model="searchKey"
              size="small"
              placeholder="检索类别名称"
              @input="filterTree"
            ></el-input>
            <el-tree
              :data="treeData"
              :props="treeProps"
              node-key="id"
              ref="treeRef"
              :current-node-key="formInline.applyCategoryId"
              @node-click="handleNodeClick"
              :filter-node-method="filterNode"
              default-expand-all
              :expand-on-click-node="false"
              :render-content="renderContent"
            >
            </el-tree>
          </div>
        </div>
        <div class="pass-list">
          <el-form
            :inline="true"
            size="small"
            :model="formInline"
            ref="formInline"
          >
            <el-form-item label="入库时间" prop="time">
              <el-date-picker
                v-model="formInline.time"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="公司名称" prop="name">
              <el-input
                v-model="formInline.name"
                placeholder="公司名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="contactPerson">
              <el-input
                v-model="formInline.contactPerson"
                placeholder="姓名"
              ></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="contactPhone">
              <el-input
                v-model="formInline.contactPhone"
                placeholder="电话"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="queryTabel()"
                >搜索</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-setting"
                @click="reset('formInline')"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
          <el-table
        :data="tableData1"
        :row-key="getRowKeys1"
        @selection-change="handleSelectionChange1"
        ref="table"
        border
        stripe
      >
        <el-table-column
          type="selection"
          width="45"
          :reserve-selection="true"
        ></el-table-column>
        <el-table-column
        prop="name"
        label="公司名称"
        ></el-table-column>
        <el-table-column
        prop="contactPerson"
        label="联系人姓名"
        ></el-table-column>
        <el-table-column
        prop="contactPhone"
        label="联系人手机"
        ></el-table-column>
        <el-table-column
        prop="storeApplyTime"
        label="入库时间"
        :formatter="formatDate"
        ></el-table-column>
      </el-table>
        <el-pagination
          class="page-footer"
          background
          layout="total,prev,pager,next,sizes,jumper"
          :total="total1"
          :page-sizes="[10, 20, 30, 40, 50]"
          @current-change="handlePageChange1"
          @size-change="handleSizeChange1"
        />
        </div>
      </div>
    </template>

    <template v-if="activeName == '1'">
      <el-form :inline="true" size="small" ref="user">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="user.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="user.phone" placeholder="手机"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="queryTabel()"
            >搜索</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-setting"
            size="small"
            @click="reset('user')"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="tableData2"
        :row-key="getRowKeys2"
        @selection-change="handleSelectionChange2"
        ref="table"
        border
        stripe
      >
        <el-table-column
          type="selection"
          width="45"
          :reserve-selection="true"
        ></el-table-column>
        <el-table-column
        prop="name"
        label="姓名"
        ></el-table-column>
        <el-table-column
        prop="phone"
        label="手机号"
        ></el-table-column>
      </el-table>
        <el-pagination
          class="page-footer"
          background
          layout="total,prev,pager,next,sizes,jumper"
          :total="total2"
          :page-sizes="[10, 20, 30, 40, 50]"
          @current-change="handlePageChange2"
          @size-change="handleSizeChange2"
        />
    </template>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="visible = false">取 消</el-button>
      <el-button
        size="small"
        type="primary"
        :disabled="isOpen"
        @click="add()"
        >确认</el-button
      >
    </div>

  </el-dialog>
</template>
<script>
import moment from "moment";
import { mapGetters, mapActions } from "vuex";
import {
  getSupplierStorePage,
  getSupplierCategoryTree
} from "@/api/supplier_api";
import { getUserList } from "@/api/system_api";
import { checkPhone, TreeArrar } from "@/utils/index";
export default {
  data() {
    return {
      user: {
        name: "",
        phone: ""
      },
      activeName: '2',
      formInline: {
        name: "",
        time: [],
        contactPerson: "",
        contactPhone: "",
        applyCategoryId: ""
      },
      filteredData: [],
      treeData: [],
      treeProps: {
        label: "categoryName",
        children: "children"
      },
      searchKey:'',
      visible: false,
      
      pageNum: 1,
      pageSize: 10,
      total1: 0,
      tableData1: [],
      total2: 0,
      tableData2: [],
      selectItem1: [],
      selectItem2: []
    };
  },
  computed: {
    ...mapGetters(["findType"]),
    isOpen() {
      let isShow = true
      if (this.activeName == '2' && this.selectItem1.length) {
        isShow = false
      } else if (this.activeName == '1' && this.selectItem2.length) {
        isShow = false
      }
      return isShow
    }
  },

  methods: {
    open(data) {
      this.total1 = 0;
      this.tableData1 = [];
      this.selectItem1 = [];
      this.activeName = '2';
      this.visible = true;
      if (this.$refs.table) {
        this.$refs.table.clearSelection();
      }
      this.treeData = data ?? [];
      this.filteredData = data ?? [];
      if (this.treeData.length) {
          this.traverseTree([data[0]])
          this.getSupplier(true);
        }
    },
    traverseTree(nodes) {
        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i];
          if (!node.children || node.children.length === 0) {
            this.formInline.applyCategoryId = node.id
            break;
          } else {
            this.traverseTree(node.children);
          }
        }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.categoryName.indexOf(value) !== -1;
    },
    filterTree() {
      const tree = this.$refs.treeRef;
      tree.filter(this.searchKey);
      // 递归过滤数据
      this.treeData = this.recursiveFilter(this.filteredData, this.searchKey);
    },
     // 递归过滤树数据的方法
    recursiveFilter(data, keyword) {
      return data.filter(item => {
        if (item.categoryName.includes(keyword)) {
          return true;
        }
        if (item.children && item.children.length > 0) {
          const filteredChildren = this.recursiveFilter(item.children, keyword);
          if (filteredChildren.length > 0) {
            item.children = filteredChildren;
            return true;
          }
        }
        return false;
      });
    },
    renderContent(h, { node, data }) {
      // 判断节点是否有子节点，有则为父节点，设置禁用属性
      const isDisabled = node.childNodes.length > 0;
      return h('span', {
        style: {
          color: isDisabled? '#ccc' : 'inherit'
        },
        attrs: {
          disabled: isDisabled
        }
      }, data.categoryName);
    },
    handleNodeClick(data) { 
      if (!data.children || data.children.length === 0) { 
        this.formInline.applyCategoryId = data.id
        this.tableData1 = [];
        this.getSupplier(true);
      }
    },
    async getUser(flag) {
      let param = {};
      param.statusFlag = "1";
      param.name = this.user.name;
      if (this.user.phone && !checkPhone(this.user.phone)) {
        this.$message.error("电话输入格式有误");
        return;
      }
      param.phone = this.user.phone;
      if (flag) {
        this.pageNum = 1;
        this.pageSize = 10;
      }
      param.pageNum = this.pageNum;
      param.pageSize = this.pageSize;
      param.userType = "1";
      const { code, data } = await getUserList(param);
      if (code == 200) {
        this.tableData2 = data.list;
        this.total2 = data.total;
      }
    },
    async getSupplier(flag) {
      let param = {};
      if (flag) {
        this.pageNum = 1;
        this.pageSize = 10;
      }
      if (
        this.formInline.contactPhone &&
        !checkPhone(this.formInline.contactPhone)
      ) {
        this.$message.error("电话输入格式有误");
        return;
      }
      if (this.formInline.time && this.formInline.time.length) {
        param.storeStartTime = this.formInline.time[0]
        param.storeEndTime = this.formInline.time[1]
       }

      param.contactPhone = this.formInline.contactPhone;
      param.name = this.formInline.name;
      param.applyCategoryId = this.formInline.applyCategoryId;
      param.pageNum = this.pageNum;
      param.pageSize = this.pageSize;
      param.queryType = this.findType["pass"];
      // param.storeStatus = "1";
      // param.isPaused = 0;
      param.tag = "1" // 供应商标签 1、合格供应商 2、暂停使用 3、黑名单
          param.storeStatus = "1" //入库状态 0.待审核 1.审核通过 2.审核拒绝
      param.isPaused = 0 // 是否暂停 1.已暂停 0.未暂停
      param.storeType = "1" //入库类型   1、入库申请 2、更新资料
      const { code, data } = await getSupplierStorePage(param);
      if (code == 200) {
        data.list.forEach(v => {
          v.id = v.userId
        });
        this.tableData1 = data.list;
        this.total1 = data.total;
      }
    },
    tabChange(e) {
      if (e.name == '2') {
        this.total1 = 0;
        this.tableData1 = [];
        this.selectItem1 = []
        this.getSupplier(true);
      } else if (e.name == '1') {
         this.total2 = 0;
        this.tableData2 = [];
         this.selectItem2 = []
        this.getUser(true);
      }
    },
    clearData() {
      
    },
    queryTabel() {
      if (this.activeName == '1') {
        this.selectItem2 = []
        this.getUser(true);
      } else {
        this.selectItem1 = []
        this.getSupplier(true);
      }
    },
    reset(formName) {
      this.$refs[formName].resetFields();
      this.queryTabel();
    },
     formatDate(row, column) {
      const date = row[column.property];
      if (date == undefined) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD  HH:mm:ss");
    },
    handlePageChange1(page) {
      this.pageNum = page;
      this.getSupplier(false);
    },
    handleSizeChange1(page) {
      this.pageSize = page;
      this.getSupplier(false);
    },
    getRowKeys1(row) {
      return row.id;
    },
    handleSelectionChange1(val) {
      let selectItem = [];
      val.forEach(item => {
        let ind = this.selectItem1.map(v => v.id);
        if (!ind.includes(item.id)) {
          selectItem.push(item);
        }
      });
      this.selectItem1 = this.selectItem1.concat(selectItem);
    },
     handlePageChange2(page) {
      this.pageNum = page;
      this.getUser(true);
    },
    handleSizeChange2(page) {
      this.pageSize = page;
      this.getUser(true);
    },
    getRowKeys2(row) {
      return row.id;
    },
    handleSelectionChange2(val) {
      let selectItem = [];
      val.forEach(item => {
        let ind = this.selectItem2.map(v => v.id);
        if (!ind.includes(item.id)) {
          selectItem.push(item);
        }
      });
      this.selectItem2 = this.selectItem2.concat(selectItem);
    },
    add() {
      if (this.activeName == "2") {
        if (this.selectItem1.length) {
          this.$emit('onOk', this.selectItem1)
          this.visible = false
        } else {
          this.$message.error('请勾选供应商数据')
        }
      } else {
        if (this.selectItem2.length) {
          this.$emit('onOk', this.selectItem2)
          this.visible = false
        } else {
          this.$message.error('请勾选用户数据')
        }
      }
    }
  }
};
</script>
<style scoped>
.pass-box{
  overflow: hidden;
}
.pass-tree{
  border: 1px solid rgb(235, 238, 244);
  width: 240px;
  float: left;
  height: auto;
}
.tree-curr .pass-tree{
  width: 43px;
}
.tree-curr .line-label{
  display: none;
}
.tree-curr .tree-prop{
  display: none;
}
.line-icon{
  font-size: 24px;
  cursor: pointer;
}
.line-ber{
margin-bottom:10px;border-bottom: 1px solid #EBEEF4;padding: 0 10px;background: #fafafa;display: flex;align-items: center;
}
.line-label{
  line-height: 40px;
  flex: 1;
}
.tree-prop {
  height: auto;
  overflow: auto;
  padding: 10px;
}
.pass-list{
  margin-left: 260px;
}
.tree-curr .pass-list{
  margin-left: 63px;
}
.psm-duo{
  margin-bottom: 10px;
}
</style>
